package com.kancy.netclass;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author huangchengkang
 * @date 2018-10-11 15:02
 */
public class NetClassLoader {
    private NetClassLoader() {}

    private volatile static NetClassLoader netClassLoader;

    private static URLClassLoader classLoader;

    private List<URL> classUrlList = new ArrayList();

    /**
     * 创建示例
     */
    public static NetClassLoader newInstance() {
        return newInstance(true);
    }
    /**
     * double check 创建示例
     * 当isSystemClassLoader = false , 类加载器为新创建
     */
    public static NetClassLoader newInstance(boolean isSystemClassLoader) {
        if(netClassLoader == null){
            synchronized (NetClassLoader.class){
                if(netClassLoader == null){
                    netClassLoader = new NetClassLoader();
                    if(isSystemClassLoader){
                        classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                    }else{
                        classLoader = new URLClassLoader(new URL[]{});
                    }
                }
            }
        }
        return netClassLoader;
    }

    /**
     * 加载
     * @param urlPaths
     */
    public void addURL(String ... urlPaths){
        if(urlPaths == null || urlPaths.length <= 0){
            throw new NullPointerException("param urls is null");
        }
        int length = urlPaths.length;
        List<URL> list = new ArrayList<URL>(length);
        for (int i = 0; i < length; i++) {
            String urlPath = null;
            try {
                urlPath = urlPaths[i];
                if(urlPath != null && urlPath.trim().length() > 0){
                    list.add(new URL(urlPath));
                }
            } catch (Exception e) {
                Logger.getLogger(NetClassLoader.class.getName()).warning(e.getMessage());
            }
        }
        addURL(list.toArray(new URL[]{}));
    }

    /**
     * 加载
     * @param urls
     */
    public void addURL(URL ... urls){
        if(urls == null || urls.length <= 0){
            throw new NullPointerException("param urls is null");
        }

        // 注册网络资源到系统加载器
        Method addURLMethod = getURLClassLoaderAddURLMethodObject();
        boolean accessible = addURLMethod.isAccessible();
        try {
            addURLMethod.setAccessible(true);
            int urlSize = urls.length;
            for (int i = 0; i < urlSize; i++) {
                if(urls[i] == null){
                    continue;
                }
                if(!classUrlList.contains(urls[i])){
                    addURLMethod.invoke(classLoader, urls[i]);
                    classUrlList.add(urls[i]);
                    Logger.getLogger(NetClassLoader.class.getName()).info("成功加载网络类库资源文件：" + urls[i].toString());
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }finally {
            addURLMethod.setAccessible(accessible);
        }
    }

    /**
     * 加载Class
     * @param className
     * @return
     * @throws ClassNotFoundException
     */
    public Class<?> loadClass(String className) throws ClassNotFoundException {
        return getClassLoader().loadClass(className);
    }

    /**
     * 获取系统类加载器
     * @return
     */
    public ClassLoader getClassLoader() {
        return classLoader;
    }

    /**
     * 获取加载资源列表
     * @return
     */
    public List<URL> getUrlResources() {
        return new ArrayList<URL>(classUrlList);
    }

    /**
     * 获取URLClassLoader的addURL方法
     * @return
     */
    private Method getURLClassLoaderAddURLMethodObject(){
        Method method = null;
        try {
            method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return method;
    }

}
